package com.xxjqr.rbac.controller;

import com.wf.captcha.ArithmeticCaptcha;
import com.xxjqr.rbac.anno.IgnoreResAdvice;
import com.xxjqr.rbac.util.RedisUtil;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static com.xxjqr.rbac.constant.Const.CAPTCHA_SESSION_KEY;


@IgnoreResAdvice
@RestController
@RequestMapping("captcha")
@AllArgsConstructor
public class CaptchaController {

    private final RedisUtil redisUtil;

    @GetMapping("getCaptcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws Exception {
        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // 生成算术类型验证码
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
        captcha.setLen(2);  // 几位数运算，默认是两位
        //captcha.getArithmeticString();  // 获取运算的公式：3+2=?

        // 把运算结果放入session中
        //session.setAttribute(captchaSessionKey, captcha.text().toLowerCase(Locale.ROOT));
        redisUtil.hset(CAPTCHA_SESSION_KEY, session.getId(), captcha.text().toLowerCase(),60);
        // 输出验证图片
        captcha.out(response.getOutputStream());
    }
}
